<template>
  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="30%" align-center>
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <!-- 仅保留：为当前规则选择角色 -->

      <!-- 为指定规则选择角色的模式 -->
      <ElFormItem v-if="ruleId" label="选择角色" prop="role_ids">
        <ElTransfer v-model="formData.role_ids" :data="roleTransferList" :titles="['可选角色', '已选角色']"
          :button-texts="['移除', '添加']" :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }" filterable filter-placeholder="搜索角色" style="text-align: left; display: inline-block" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-ripple>提交</el-button>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import {
  createRoleDataPermission,
  updateRoleDataPermission,
  fetchRuleRolePermissions,
  type RoleDataPermissionResponse
} from '@/api/system/data-permission'
import { fetchRoleList } from '@/api/system/role'

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  ruleId?: number | null  // 当传入ruleId时，表示为指定规则添加角色关联
  editData?: Partial<RoleDataPermissionResponse>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const dialogTitle = computed(() => {
  if (props.ruleId) {
    return props.type === 'add' ? '为规则添加角色关联' : '编辑角色关联'
  }
  return props.type === 'add' ? '添加角色权限关联' : '编辑角色权限关联'
})

// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  role_id: null as number | null,
  rule_ids: [] as number[],
  role_ids: [] as number[]  // 为规则选择角色时使用
})

// 角色列表和转换后的列表
const roleList = ref<any[]>([])
const roleTransferList = computed(() =>
  roleList.value.map(role => ({
    key: role.id,
    label: role.name,
    disabled: false
  }))
)

// 已移除：规则列表（本弹窗仅选择角色）

// 表单验证规则
const rules: FormRules = {
  role_ids: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const res = await fetchRoleList({ current: 1, size: 100 })
    roleList.value = res.items || []
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 已移除：获取权限规则列表（本弹窗不再展示规则选择）

// 初始化表单
const initFormData = () => {
  const isEdit = props.type === 'edit' && props.editData
  const row = props.editData || {}

  // 为规则选择角色的模式（仅保留该模式）
  Object.assign(formData, {
    role_ids: []
  })
}

watch(
  () => [props.visible, props.type, props.editData],
  async ([visible]) => {
    if (visible) {
      initFormData()
      await getRoleList()

      // 打开时预填：当前规则已关联的角色
      if (props.ruleId) {
        try {
          const res = await fetchRuleRolePermissions(props.ruleId)
          formData.role_ids = Array.isArray(res) ? res.map((item: any) => item.role_id) : []
        } catch (error) {
          console.error('获取当前规则已关联角色失败:', error)
        }
      }
      nextTick(() => formRef.value?.clearValidate())
    }
  },
  { immediate: true }
)

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (props.ruleId) {
        // 为规则添加角色关联的模式
        const roleIds = formData.role_ids
        for (const roleId of roleIds) {
          await createRoleDataPermission({
            role_id: roleId,
            rule_id: props.ruleId
          })
        }
      } else {
        // 为角色选择规则的模式
        const payload = {
          role_id: formData.role_id!,
          rule_ids: formData.rule_ids
        }

        if (props.type === 'add') {
          // 为角色添加多个规则关联
          for (const ruleId of payload.rule_ids) {
            await createRoleDataPermission({ role_id: payload.role_id, rule_id: ruleId })
          }
        } else {
          const id = Number(props.editData?.id)
          if (!id) {
            ElMessage.error('缺少关联ID，无法编辑')
            return
          }
          await updateRoleDataPermission(id, payload)
        }
      }

      ElMessage.success('提交成功')
      emit('submit')
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-transfer) {
  .el-transfer-panel {
    width: 200px;
  }
}
</style>